// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <melon/benchmark.h>
#include <melon/init/init.h>
#include <pollux/functions/macros.h>
#include <pollux/functions/registerer.h>
#include <pollux/functions/lib/benchmarks/FunctionBenchmarkBase.h>
#include <pollux/functions/prestosql/registration/registration_functions.h>

using namespace kumo::pollux;
using namespace kumo::pollux::exec;
using namespace kumo::pollux::test;

namespace {

template <typename T>
struct NotScalarFunction {
  bool call(bool& result, const bool& arg) {
    result = !arg;
    return true;
  }
};

class NotBenchmark : public functions::test::FunctionBenchmarkBase {
 public:
  NotBenchmark() : FunctionBenchmarkBase() {
    functions::prestosql::registerArithmeticFunctions();
    register_function<NotScalarFunction, bool, bool>({"not_scalar"});
  }

  void run(const std::string& functionName) {
    melon::BenchmarkSuspender suspender;
    constexpr vector_size_t size = 1000;

    // False in even positions: False, True, False, True, .....; with some nulls
    auto evenFalse = vectorMaker_.row_vector({vectorMaker_.flat_vector<bool>(
        size,
        [](auto row) { return row % 2 == 1; },
        VectorMaker::null_every(5))});
    auto exprSet = compileExpression(
        fmt::format("{}(c0)", functionName), evenFalse->type());
    suspender.dismiss();

    doRun(exprSet, evenFalse);
  }

  void doRun(ExprSet& exprSet, const RowVectorPtr& row_vector) {
    int cnt = 0;
    for (auto i = 0; i < 100; i++) {
      cnt += evaluate(exprSet, row_vector)->size();
    }
    melon::doNotOptimizeAway(cnt);
  }
};

BENCHMARK(scalarNot) {
  NotBenchmark benchmark;
  benchmark.run("not_scalar");
}

BENCHMARK_RELATIVE(vectorizedNot) {
  NotBenchmark benchmark;
  benchmark.run("not");
}

} // namespace

int main(int argc, char** argv) {
  melon::Init init{&argc, &argv};

  melon::runBenchmarks();
  return 0;
}
